#include "CoffParser.h"

#include <fstream>
#include <iostream>

#include <windows.h>
#include <string.h>

using namespace std;


void CoffParser::init(){
    memset(&header, 0, sizeof(IMAGE_ROM_HEADERS));
}

CoffParser::CoffParser(LPCSTR szFile=NULL){
    init();

    ifstream ifCoffFile(szFile, ios::binary);
    if(!ifCoffFile)return;


    ifCoffFile.seekg(0, ios::end);
    uiFileSize = ifCoffFile.tellg();

    szBuffer = new char[uiFileSize];
    memset(szBuffer, 0 , uiFileSize);

    ifCoffFile.seekg(0, ios::beg);

    ifCoffFile.read(szBuffer, uiFileSize);
    ifCoffFile.close();

    // we should read file header first, and then optional header.

    // IMAGE_SIZEOF
    // IMAGE_FIRST_SECTION
    memcpy(&header, szBuffer, IMAGE_SIZEOF_FILE_HEADER);
    if(header.FileHeader.SizeOfOptionalHeader > 0) {
        memcpy(&header + IMAGE_SIZEOF_FILE_HEADER, szBuffer + IMAGE_SIZEOF_FILE_HEADER, header.FileHeader.SizeOfOptionalHeader);
    }
}

const IMAGE_ROM_HEADERS& CoffParser::getHeader()const{
    return header;
}


CoffParser::~CoffParser() {
    if(szBuffer) {
        delete[] szBuffer;
        szBuffer = NULL;
    }
}
